Here in this blog I will show you a small demo of ThreadStart delegate which is used to create starting point in Thread. In this demonstration I used Thread class which is used to create object of Thread, ThreadStart class which work as delegate for Thread class and work for starting point for current thread and finally I used Sleep() method of thread class. When we want to pause execution of current thread then we call Sleep() method of thread class and pass interval in milliseconds.
Following example demonstrate use of ThreadStart class for creating thread in c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadStartDemo
{
class ThreadDemo
{
static void Main(string[] args)
{
Thread th; //Declaring reference variable of thread class.
//Creating object of ThreadStart class.
ThreadStart thStart = new ThreadStart(DoWork);
for (int i = 1; i < 5; i++)
{
Console.WriteLine("Starting Thread : {0}", i);
//Creating object of thread class and passing thread start
//object as parameter to thread class.
th = newThread(thStart);
th.Name = i.ToString();
//Starting new thread by calling Start() method.
th.Start();
}
Console.ReadLine();
}
///<summary>
/// DoWork method is passed to ThreadStart constructor.
/// This methood is used to display total iteration of current
/// executing thread and thread name.
/// Thread.Sleep() method is used to Pause executing thread.
///</summary>
staticvoid DoWork()
{
for (int count = 1; count <= 10; count++)
{
Console.WriteLine("Thread {0} : iteration : {1}", Thread.CurrentThread.Name, count);
Thread.Sleep(10);
}
}
}
}
After executing this class you will see following output. This output may be vary depending upon priority set to thread.
Starting Thread : 1
Starting Thread : 2
Thread 1 : iteration : 1
Thread 2 : iteration : 1
Starting Thread : 3
Starting Thread : 4
Thread 3 : iteration : 1
Thread 4 : iteration : 1
Thread 2 : iteration : 2
Thread 1 : iteration : 2
Thread 4 : iteration : 2
Thread 3 : iteration : 2
Thread 1 : iteration : 3
Thread 3 : iteration : 3
Thread 2 : iteration : 3
Thread 4 : iteration : 3
Thread 1 : iteration : 4
Thread 2 : iteration : 4
Thread 4 : iteration : 4
Thread 3 : iteration : 4
Thread 1 : iteration : 5
Thread 3 : iteration : 5
Thread 4 : iteration : 5
Thread 2 : iteration : 5
Thread 1 : iteration : 6
Thread 2 : iteration : 6
Thread 4 : iteration : 6
Thread 3 : iteration : 6
Thread 1 : iteration : 7
Thread 4 : iteration : 7
Thread 2 : iteration : 7
Thread 3 : iteration : 7
Thread 1 : iteration : 8
Thread 4 : iteration : 8
Thread 2 : iteration : 8
Thread 3 : iteration : 8
Thread 1 : iteration : 9
Thread 4 : iteration : 9
Thread 2 : iteration : 9
Thread 3 : iteration : 9
Thread 1 : iteration : 10
Thread 4 : iteration : 10
Thread 3 : iteration : 10
Thread 2 : iteration : 10
Thanks for reading this blog.
Anonymous User
09-Apr-2019Thanks for the post.